#include "AppSearchResponseCmd.h"

AppSearchResponseCmd::AppSearchResponseCmd(QObject *parent) :
    BaseCmd(parent)
{
    this->m_protocolType = ProtocolType::CloudProtocol;
    this->m_functionCode = FunctionCode;
}

QByteArray AppSearchResponseCmd::strUserToArrayUser(UserStruct user)
{
    QByteArray array;
    quint16 strLength;

    strLength = user.name().toLocal8Bit().size();
    array.append(DataTypeConver::intToByteArray(strLength,2));
    array.append(user.name());

    strLength = user.account().size();
    array.append(DataTypeConver::intToByteArray(strLength,2));
    array.append(user.account());

    strLength = user.role().size();
    array.append(DataTypeConver::intToByteArray(strLength,2));
    array.append(user.role());

    strLength = user.permissionList().size();
    array.append(DataTypeConver::intToByteArray(strLength,2));
    for(int i=0; i<user.permissionList().size(); i++)
    {
        strLength = user.permissionList().at(i).size();
        array.append(DataTypeConver::intToByteArray(strLength,2));
        array.append(user.permissionList().at(i));

    }
    return array;
}


Package AppSearchResponseCmd::toPackage()
{
    Package package;
    QByteArray body;

    quint16 strLength;

    strLength = m_mac.length();
    body.append(DataTypeConver::intToByteArray(strLength,2));
    body.append(m_mac);

    body.append(DataTypeConver::intToByteArray(m_port,2));

    QList<UserStruct> childUserList;
    for(int i=0; i<m_userList.size(); i++)
    {
        bool isPrimary = m_userList.at(i).isPrimary();
        if(isPrimary)
        {
            UserStruct fatherUser = m_userList.at(i);
            body.append(strUserToArrayUser(fatherUser));
        }
        else
        {
            childUserList.append(m_userList.at(i));
        }
    }

    quint16 childUserSize = childUserList.size();
    body.append(DataTypeConver::intToByteArray(childUserSize,2));

    for(int i =0; i<childUserList.size(); i++)
    {
        UserStruct childUser = childUserList.at(i);
        body.append(strUserToArrayUser(childUser));
    }

    body = encrypt(body,KeyType::AES);

    package.setId(m_cmdId);
    package.setFunction(FunctionCode);
    package.setBody(body);

    return package;
}

void AppSearchResponseCmd::unPackage(Package package)
{
    m_cmdId = package.id();
}
QString AppSearchResponseCmd::mac() const
{
    return m_mac;
}

void AppSearchResponseCmd::setMac(const QString &mac)
{
    m_mac = mac;
}
quint16 AppSearchResponseCmd::port() const
{
    return m_port;
}

void AppSearchResponseCmd::setPort(const quint16 &port)
{
    m_port = port;
}
QList<UserStruct> AppSearchResponseCmd::userList() const
{
    return m_userList;
}

void AppSearchResponseCmd::setUserList(const QList<UserStruct> &userList)
{
    m_userList = userList;
}




